package cn.wolfcode.rabc.controller;
// 需求： 要求请求路径为 /employee/list

import cn.wolfcode.rabc.anno.RequiredPermission;
import cn.wolfcode.rabc.domain.Department;
import cn.wolfcode.rabc.domain.Employee;
import cn.wolfcode.rabc.domain.Role;
import cn.wolfcode.rabc.qo.EmployeeQueryObject;
import cn.wolfcode.rabc.qo.JsonResult;
import cn.wolfcode.rabc.service.IDepartmentService;
import cn.wolfcode.rabc.service.IEmployeeService;
import cn.wolfcode.rabc.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    // 处理查询所有员工请求
    // 把查询的方法的封装参数的形参改成 EmployeeQueryObject 类型，并贴上 @ModelAttribute("qo")
    @RequestMapping("/list")
    @RequiredPermission(name = "员工查询", expression = "employee:list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        // System.out.println("======qo=============" + qo);
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        List<Department> departments = departmentService.listAll();
        // 查询所有部门往模型存入，提供数据，让员工列表页面是现实出来给用户选择
        model.addAttribute("departments", departments);
        return "employee/list";
    }


    // 处理删除请求
    // 请求路径为：/employee/delete
    @RequestMapping("/delete")
    @RequiredPermission(name = "员工删除", expression = "employee:delete")
    public String delete(Long id) {
        if (id != null) {
            // 删除员工角色中间表（employee_role）,通过员工id删除
            employeeService.deleteByEmployeeId(id);

            employeeService.delete(id);
        }
        return "redirect:/employee/list"; // 重新访问一次/list
    }

    @Autowired
    private IRoleService RoleService;

    // 处理 去新增 / 去修改
    // 新增员工时，部门不要输入而是选择
    @RequestMapping("/input")
    @RequiredPermission(name = "员工去修改或新增", expression = "employee:input")
    public String input(Long id, Model model) {

        List<Department> departments = departmentService.listAll();
        List<Role> roles = RoleService.listAll();
        // 查询所有部门往模型存入，提供数据，让员工新增修改时显示出来以供用户选择
        model.addAttribute("departments", departments);
        model.addAttribute("roles", roles);

        if (id != null) {
            // 去修改
            Employee employee = employeeService.get(id);
            // 角色回显需要的数据(通过员工id查询到角色)
            List<Role> roleList = employeeService.queryByEmployeeId(id);

            model.addAttribute("roleList", roleList);
            model.addAttribute("employee", employee);
        }
        return "employee/input";
    }


    // 处理 新增 / 修改
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "员工修改或新增", expression = "employee:saveOrUpdate")
    @ResponseBody
    public JsonResult input(Employee employee, Long[] roleIds) {

        try {
            if (employee.getId() == null) {
                // 新增
                employeeService.save(employee);
                // 往中间表中存入(employee_role)数据
                insertRelation(employee, roleIds);
            } else {
                // 修改
                // 更新中间角色表（employee_role）一般使用的方式是先删除旧有的关系，再加新的关系。
                // 更新员工表

                employeeService.deleteByEmployeeId(employee.getId());
                insertRelation(employee, roleIds);
                employeeService.update(employee);
            }
        } catch (Exception e) {
            return new JsonResult("操作失败", false);
        }
        return new JsonResult("操作成功", true);
    }


    // 向中间表插入数据
    private void insertRelation(Employee employee, Long[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                employeeService.insertRelation(roleId, employee.getId());
            }
        }
    }

}
